package io.renren.common.utils;

import io.renren.modules.sp.dao.SpMatchDao;
import io.renren.modules.sp.dao.SpMatchItemDao;
import io.renren.modules.sp.dao.SpMatchItemTeamDao;
import io.renren.modules.sp.dao.SpTeamDao;
import io.renren.modules.sp.entity.*;
import io.renren.modules.sp.service.TAreaService;
import io.renren.modules.sys.dao.SysCommDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class CertificateNoUtils {

    @Autowired
    private SysCommDao commDao;
    @Autowired
    private SpMatchItemTeamDao spMatchItemTeamDao;
    @Autowired
    private SpMatchItemDao spMatchItemDao;
    @Autowired
    private SpMatchDao spMatchDao;
    @Autowired
    private SpTeamDao teamDao;
    @Autowired
    private TAreaService areaService;

    /**
     * 生成荣誉证书编号
     * @param matchTeamId
     * @param type  T:老师 S:选手
     * @param lastForNo 后四位流水号
     * @return
     */
    public Result<String> getCertificateNo(Long matchTeamId, String type, String lastForNo){

        SpMatchItemTeamEntity spMatchItemTeam = spMatchItemTeamDao.selectById(matchTeamId);
        SpMatchItemEntity itemEntity = spMatchItemDao.selectById(spMatchItemTeam.getMatchItemId());
        SpMatchEntity matchEntity = spMatchDao.selectById(itemEntity.getMatchId());
        SpTeamEntity team = teamDao.selectById(spMatchItemTeam.getTeamId());

        //查询省份
        TAreaEntity province = areaService.getByCode(team.getProvince());
        //查询市
        TAreaEntity city = areaService.getByCode(team.getCity());
        if(province == null){
            return new Result().error("代表队未维护城市！");
        }
        //省份简称
        String provinceName = province.getCode();
        //100301:X小学  100302:C初中 100303:G 高中 领队：L
        String groupName = spMatchItemTeam.getGroupId() == 100301 ? "X" :
                spMatchItemTeam.getGroupId() == 100302 ? "C" :
                        spMatchItemTeam.getGroupId() == 100303 ? "G" :
                                spMatchItemTeam.getGroupId() == 100304 ? "X" :
                                        spMatchItemTeam.getGroupId() == 100305 ? "X" :
                                                spMatchItemTeam.getGroupId() == 100306 ? "X" :
                                                        spMatchItemTeam.getGroupId() == 100307 ? "G" : "";
                ;
        if (province == null || StringUtils.isBlank(province.getJiancheng())) {
            return new Result().error("赛事未维护省份，或者省份简称为空！");
        }
        if (StringUtils.isBlank(team.getTeamCode())) {
            return new Result().error("代表队编码不能为空！");
        }
        if (StringUtils.isBlank(matchEntity.getTimes())) {
            return new Result().error("赛事届数不能为空！");
        }
        if (StringUtils.isBlank(groupName)) {
            return new Result().error("赛项报名，参赛组别不能为空！");
        }
        if (matchEntity.getMatchLevel() == null || matchEntity.getMatchLevel() > 3 || matchEntity.getMatchLevel() < 0) {
            return new Result().error("赛事级别维护错误！");
        }
        /*if(StringUtils.isBlank(itemEntity.getAddr())){
            return new Result().error("比赛场地不能为空！");
        }*/
        //没有生成
        char leveName = "ABC".charAt(matchEntity.getMatchLevel() - 1);

        Integer level = matchEntity.getMatchLevel();
        String privinceCode = "";
        if(level == 1){
            privinceCode = "100";
        } else if (level==2) {
            privinceCode = "0" + provinceName.substring(0,2);
        }

        String cityCode = city.getQuhao();
        // 如果城市为空，取省的编码
        if(StringUtils.isBlank(cityCode)){
            cityCode = province.getQuhao();
        }
        // 城市码4位的，去掉首位
        if(cityCode !=null && cityCode.length()==4){
            cityCode = cityCode.substring(1);
        }

        //队内序号
        // String order = queryTeamMemberNum(itemEntity.getId(), type);
        //EDE	07	A	100	12	T	021	0	0234
        //大赛简称	届数	国赛	国赛固定100	比赛项目	指导老师	城市区号 上海	指导老师固定为0	"赛项内流水号
        //指导老师则按流水号排序"
        StringBuffer cardCode = new StringBuffer("EDE");
        cardCode.append(matchEntity.getTimes())
                .append(leveName)
                .append(privinceCode)
                .append(itemEntity.getCode())
                .append(type)
                .append(StringUtils.isNotBlank(cityCode)?cityCode: privinceCode)
                .append("T".equals(type)?"0":groupName)
                .append(lastForNo);

        return new Result<String>().ok(cardCode.toString());
    }

    /**
     * 生成荣誉证书编号
     * @param matchId
     * @param teamId
     * @param matchItemId
     * @param lastForNo 后四位流水号
     * @return
     */
    public Result<String> getCertificateNoTeacher(Long matchId, Long teamId, String matchItemId, String lastForNo){
        // SpMatchItemTeamEntity spMatchItemTeam = spMatchItemTeamDao.selectById(matchTeamId);
        SpMatchItemEntity itemEntity = spMatchItemDao.selectById(matchItemId);
        SpMatchEntity matchEntity = spMatchDao.selectById(matchId);
        SpTeamEntity team = teamDao.selectById(teamId);
        //查询省份
        TAreaEntity province = areaService.getByCode(team.getProvince());
        //查询市
        TAreaEntity city = areaService.getByCode(team.getCity());
        //省份简称
        String provinceName = province.getCode();
        if (province == null || StringUtils.isBlank(province.getJiancheng())) {
            return new Result().error("赛事未维护省份，或者省份简称为空！");
        }
        if (StringUtils.isBlank(team.getTeamCode())) {
            return new Result().error("代表队编码不能为空！");
        }
        if (StringUtils.isBlank(matchEntity.getTimes())) {
            return new Result().error("赛事届数不能为空！");
        }
        if (matchEntity.getMatchLevel() == null || matchEntity.getMatchLevel() > 3 || matchEntity.getMatchLevel() < 0) {
            return new Result().error("赛事级别维护错误！");
        }
        //没有生成
        char leveName = "ABC".charAt(matchEntity.getMatchLevel() - 1);

        Integer level = matchEntity.getMatchLevel();
        String privinceCode = "";
        if(level == 1){
            privinceCode = "100";
        } else if (level==2) {
            privinceCode = "0" + provinceName.substring(0,2);
        }

        String cityCode = city.getQuhao();
        // 如果城市为空，取省的编码
        if(StringUtils.isBlank(cityCode)){
            cityCode = province.getQuhao();
        }
        // 城市码4位的，去掉首位
        if(cityCode !=null && cityCode.length()==4){
            cityCode = cityCode.substring(1);
        }

        //队内序号
        // String order = queryTeamMemberNum(itemEntity.getId(), type);
        //EDE	07	A	100	12	T	021	0	0234
        //大赛简称	届数	国赛	国赛固定100	比赛项目	指导老师	城市区号 上海	指导老师固定为0	"赛项内流水号
        //指导老师则按流水号排序"
        StringBuffer cardCode = new StringBuffer("EDE");
        cardCode.append(matchEntity.getTimes())
                .append(leveName)
                .append(privinceCode)
                .append(itemEntity.getCode())
                .append("T")
                .append(StringUtils.isNotBlank(cityCode)?cityCode: privinceCode)
                .append("0")
                .append(lastForNo);

        return new Result<String>().ok(cardCode.toString());
    }


    /**
     * 查询队员序号
     * @param
     * @param
     * @param type
     * @return
     */
    public Double queryTeamMemberNum(Long matchItemId, Long groupId, String type, Long matchId) {
        Map<String,Object> param = new HashMap();
        String sql = "SELECT" +
                " IFNULL(max(RIGHT ( itu.certificate, 4 )) ,0) + 1 count" +
                " FROM" +
                " sp_match_item_team_user itu" +
                " left join sp_match_item_team it on itu.match_item_team_id = it.id" +
                " left join sp_match_item mi on it.match_item_id = mi.id" +
                " where 1=1";
        // 指导老师
        if("T".equals(type)){
            sql += " and itu.type = 2";
            sql += " and mi.match_id = #{p.matchId} ";
            sql += " and mi.id = #{p.matchItemId} ";
            param.put("matchId",matchId);
            param.put("matchItemId",matchItemId);
        }else{
            sql += " and itu.type = 1";
            sql += " and mi.id = #{p.matchItemId}";
            param.put("matchItemId",matchItemId);

            if(groupId != null){
                if(groupId.intValue() != 0) {
                    sql += " and it.group_id = #{p.groupId}";
                    param.put("groupId", groupId);
                }else{
                    sql += " and it.group_id in (100304, 100305)";
                }
            }
        }
        sql += " and it.status in (1,2,4,5,6)";
        sql += " and itu.certificate is not null";
        Map<String,Object> map = commDao.query(sql,param);
        return (Double) map.get("count");
    }


}
